package com.qiulingcloud.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiulingcloud.commonsserver.exception.BusinessException;
import com.qiulingcloud.commonsserver.exception.code.BaseResponseCode;
import com.qiulingcloud.commonsserver.entity.SysUser;
import com.qiulingcloud.commonsserver.entity.TestOrder;

import com.qiulingcloud.commonsserver.entity.vo.PageReqVO;
import com.qiulingcloud.commonsserver.entity.vo.PageVO;
import com.qiulingcloud.commonsserver.utils.PageUtil;
import com.qiulingcloud.order.mapper.TestOrderMapper;
import com.qiulingcloud.order.service.TestOrderService;
import com.qiulingcloud.order.service.feign.FeignUserService;
import com.qiulingcloud.order.vo.req.TestOrderAddReqVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangqiang
 * @since 2020-04-27
 */
@Service
public class TestOrderServiceImpl extends ServiceImpl<TestOrderMapper, TestOrder> implements TestOrderService {

    @Autowired
    private TestOrderMapper testOrderMapper;
    @Autowired
    private FeignUserService feignUserService;

    @Override
    public PageVO<TestOrder> pageInfo(PageReqVO vo) {
        QueryWrapper<TestOrder> wrapper = PageUtil.parseWhereSql(vo.getConditionJson(), vo.isAsc(), vo.getOrderFields());
        Page<TestOrder> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        IPage<TestOrder> testOrderIPage = testOrderMapper.selectPage(page, wrapper);
        List<TestOrder> orderList = testOrderIPage.getRecords();
        orderList.forEach(order -> {
            //TODO 这里需要添加用户信息
            SysUser sysUser = feignUserService.gerUserByUserId(order.getUserId());
            if(sysUser.getId().equals(String.valueOf(BaseResponseCode.ERROR.getCode()))) {
                throw new BusinessException(BaseResponseCode.DOWNSTREAM_ERROR);
            }
            order.setPhone(sysUser.getPhone());
            order.setUserName(sysUser.getRealName());
        });
        testOrderIPage.setRecords(orderList);
        return PageUtil.getPageVO(testOrderIPage);
    }

    @Override
    public void createOrder(TestOrderAddReqVO vo, String userId) {
        TestOrder order = new TestOrder();
        BeanUtils.copyProperties(vo, order);
        order.setUserId(userId);
        int insert = testOrderMapper.insert(order);
        if(insert == 0) {
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }
}
